﻿using System;
using ServiceStack.Redis;

namespace Redis.Core
{
    /// <summary>
    /// Redis客户端对象
    /// </summary>
    public abstract class RedisBase : IDisposable
    {
        protected RedisBase(IRedisClient redisClient)
        {
            Redis = redisClient;
            LastSave = Redis.LastSave;
        }

        /// <summary>
        /// 销毁对象
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    Redis.Dispose();
                    Redis = null;
                }
            }
            this._disposed = true;
        }
        /// <summary>
        /// 销毁对象
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 保存数据DB文件到硬盘
        /// </summary>
        public void Save()
        {
            Redis.Save();
        }
        /// <summary>
        /// 清空所有键
        /// </summary>
        public void Flush()
        {
            Redis.FlushAll();
            //Redis.FlushDb();
        }

        /// <summary>
        /// 获取一个锁
        /// </summary>
        /// <param name="Key">锁的键</param>
        /// <returns></returns>
        public IDisposable Lock(String Key)
        {
            return Redis.AcquireLock(Key);
        }

        /// <summary>
        /// 停止所有客户端，保存，关闭Redis服务
        /// </summary>
        public void Shutdown()
        {
            Redis.Shutdown();
            Redis.WriteAll(new System.Collections.Generic.List<RedisBase>());
        }
        



        /// <summary>
        /// 获取一个锁
        /// </summary>
        /// <param name="Key">锁的键</param>
        /// <param name="timeOut">超时时间</param>
        /// <returns></returns>
        public IDisposable Lock(String Key,TimeSpan timeOut)
        {
            return Redis.AcquireLock(Key, timeOut);
        }

        /// <summary>
        /// 获取一个锁
        /// </summary>
        /// <param name="Key">锁的键</param>
        /// <param name="milliseconds">超时时间 毫秒</param>
        /// <returns></returns>
        public IDisposable Lock(String Key, Int32 milliseconds)
        {
            return Redis.AcquireLock(Key, new TimeSpan(0,0,0,0, milliseconds));
        }

        /// <summary>
        /// 异步保存数据DB文件到硬盘
        /// </summary>
        public void SaveAsync()
        {
            Redis.SaveAsync();
        }

        protected IRedisClient Redis { get; private set; }

        private bool _disposed = false;


        public DateTime LastSave { get; set; }
    }


}
